<script setup>
import { inject, ref, reactive, nextTick } from "vue";
import { goPage } from "@/utils/newpage";
import {
  onShow,
  onPullDownRefresh,
  onReachBottom,
  onLoad,
  onReady,
} from "@dcloudio/uni-app";
import { formatPrice } from "@/utils/formatPrice";
import listicon0 from "@/static/team/shopkeeper/icon-gm0.png";
import listicon1 from "@/static/team/shopkeeper/icon-gm1.png";
import listicon2 from "@/static/team/shopkeeper/icon-gm2.png";
import listicon3 from "@/static/team/shopkeeper/icon-gm3.png";
import listicon4 from "@/static/team/shopkeeper/icon-gm4.png";
import listicon5 from "@/static/team/shopkeeper/icon-gm5.png";
import listicon6 from "@/static/team/shopkeeper/icon-gm6.png";
import listicon7 from "@/static/team/shopkeeper/icon-gm7.png";
import listicon8 from "@/static/team/shopkeeper/icon-gm8.png";
import listicon9 from "@/static/team/shopkeeper/icon-gm9.png";
import listicon10 from "@/static/team/shopkeeper/icon-gm10.png";
import listicon11 from "@/static/team/shopkeeper/icon-gm12.png";
import {
  mine,
  userinfo,
  getMyShop,
  statistics,
  shopEdit,
} from "@/services/user";

// if (!user.userInfo || (user.userInfo && !user.userInfo.phone)) {
//   uni.switchTab({
//     url: "/pages/my/index",
//   });
// }
// const opts = ref({
//   color: [
//     "#1890FF",
//     "#91CB74",
//     "#FAC858",
//     "#EE6666",
//     "#73C0DE",
//     "#3CA272",
//     "#FC8452",
//     "#9A60B4",
//     "#ea7ccc",
//   ],
//   padding: [15, 10, 0, 15],
//   enableScroll: false,
//   legend: {},
//   xAxis: {
//     disableGrid: true,
//   },
//   yAxis: {
//     gridType: "dash",
//     dashLength: 2,
//   },
//   extra: {
//     line: {
//       type: "straight",
//       width: 2,
//       activeType: "hollow",
//     },
//   },
// });
const opts = ref({
  color: [
    "#1890FF",
    "#91CB74",
    "#FAC858",
    "#EE6666",
    "#73C0DE",
    "#3CA272",
    "#FC8452",
    "#9A60B4",
    "#ea7ccc",
  ],
  padding: [15, 15, 0, 5],
  enableScroll: false,
  legend: {},
  xAxis: {
    disableGrid: true,
  },
  yAxis: {
    data: [
      {
        min: 0,
      },
    ],
  },
  extra: {
    column: {
      type: "meter",
      width: 30,
      activeBgColor: "#000000",
      activeBgOpacity: 0.08,
      meterBorder: 3,
      meterFillColor: "#EBFBD6",
    },
  },
});
const chartData = ref({});
onReady(() => {
  getServerData();
});
const getServerData = () => {
  // //模拟从服务器获取数据时的延时
  setTimeout(() => {
    //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
    // let res = {
    //   categories: ["2018", "2019", "2020", "2021", "2022", "2023"],
    //   series: [
    //     {
    //       name: "成交量A",
    //       data: [35, 8, 25, 37, 4, 20],
    //     },
    //     {
    //       name: "成交量B",
    //       data: [70, 40, 65, 100, 44, 68],
    //     },
    //     {
    //       name: "成交量C",
    //       data: [100, 80, 95, 150, 112, 132],
    //     },
    //   ],
    // };
    // chartData.value = JSON.parse(JSON.stringify(res));
  }, 500);
};

userinfofun();

const level_id = ref("");
const area_level = ref("");
const myShopList = ref([]);
const selectshopid = ref("");
const selectshopname = ref("");
const selectshopobj = ref(null);
const order_count = ref(0);

const show = ref(false);
const columns = ref([
  [
    {
      label: "雪月夜",
      // 其他属性值
      id: 2021,
      // ...
    },
    {
      label: "冷夜雨",
      id: 804,
    },
  ],
]);

const confirmfun = (value) => {
  selectshopid.value = value.value[0].id;
  selectshopname.value = value.value[0].shop_name;
  selectshopobj.value = value.value[0];
  show.value = false;
  statisticsfun();
};
const closefun = () => {
  show.value = false;
};

const getMyShopfun = () => {
  getMyShop().then((res) => {
    console.log(res);
    myShopList.value = res.data;
    columns.value = [res.data];
    console.log(columns.value);
    selectshopid.value = res.data[0].id;
    selectshopname.value = res.data[0].shop_name;
    selectshopobj.value = res.data[0];
    statisticsfun();
  });
};
const getSelectShopfun = () => {
  show.value = true;
};
getMyShopfun();
async function userinfofun() {
  let res = await userinfo();
  level_id.value =
    res.data.level && res.data.level.id ? res.data.level.id : 201;
  if (res.data.area && res.data.area.level) {
    area_level.value = res.data.area.level;
  } else {
    area_level.value = "";
  }

  teamList.value.forEach((item, index) => {
    if (item.level_id) {
      if (item.level_id >= level_id.value) {
        teamList.value.splice(index, teamList.value.length);
      }
    }
    if (item.level) {
      if (area_level.value) {
        if (item.level < area_level.value) {
          teamList.value.splice(index, 1);
        }
      } else {
        teamList.value.splice(index, 1);
      }
    }
  });
  teamList2.value.forEach((item, index) => {
    if (item.level) {
      if (area_level.value) {
        if (item.level < area_level.value) {
          teamList2.value.splice(index, 1);
        }
      } else {
        teamList2.value.splice(index, teamList2.value.length);
      }
    }
  });
}

const gokcfun = () => {
  uni.navigateTo({
    url:
      "/pages/cloudlibrary/inventoryRecords/index?status=4&shop_id=" +
      selectshopid.value,
  });
};

const list = ref([
  {
    name: "我的库存",
    icon: listicon1,
    num: "",
    url: "/pages/cloudlibrary/mystock/index?status=0",
  },
  // {
  //   name: "云仓补货",
  //   icon: listicon2,
  //   num: "",
  //   url: "/pages/cloudlibrary/replenishment/index?status=1",
  // },
  // {
  //   name: "云仓提货",
  //   icon: listicon3,
  //   num: "",
  //   url: "/pages/cloudlibrary/takegood/index?status=2",
  // },
  // {
  //   name: "商品赠送",
  //   icon: listicon4,
  //   num: "",
  //   url: "/pages/cloudlibrary/productGift/index?status=3",
  // },
  {
    name: "库存变动记录",
    icon: listicon5,
    num: "",
    url: "/pages/cloudlibrary/inventoryRecords/index?status=4",
  },
  // {
  //   name: "商家订单",
  //   icon: listicon11,
  //   num: "",
  //   url: "/pages/order/orderlist/index?status=-2",
  // },
]);

const teamList = ref([
  {
    name: "会员",
    icon: listicon0,
    num: 0,
    level_id: 101,
    url: "/pages/team/teamlist/index?type=101",
  },
  {
    name: "店主",
    icon: listicon6,
    num: 0,
    level_id: 201,
    url: "/pages/team/teamlist/index?type=201",
  },
  {
    name: "经销商",
    icon: listicon7,
    num: 0,
    level_id: 301,
    url: "/pages/team/teamlist/index?type=301",
  },
  {
    name: "服务中心",
    icon: listicon8,
    num: 0,
    url: "/pages/team/teamlist/index?type=401",
    level_id: 401,
  },
]);
const teamList2 = ref([
  {
    name: "区级独家代理",
    icon: listicon9,
    num: 0,
    url: "/pages/team/shopkeeper/area?type=3",
    level: 3,
  },
  {
    name: "市级独家代理",
    icon: listicon10,
    num: 0,
    url: "/pages/team/shopkeeper/area?type=2",
    level: 2,
  },
]);

const newPage = (item) => {
  goPage(item.url);
};
const balance = ref({});

minefun();

async function minefun() {
  let res = await mine();
  balance.value = res.data;
}

const gopayment = () => {
  uni.navigateTo({
    url: "/pages/mine/proxyPayment",
  });
};
const gobalance = () => {
  uni.navigateTo({
    url: "/pages/servicereward/myreward/balance",
  });
};

const godetlist = () => {
  uni.navigateTo({
    url: "/pages/servicereward/myreward/rewardlist",
  });
};

const goygfun = () => {
  uni.navigateTo({
    url: "/pages/servicereward/myreward/rewardyg",
  });
};

const goinvoice = () => {
  // uni.navigateTo({
  //   url: "/pages/servicereward/myreward/rewardyg",
  // });

  uni.showToast({
    title: "正在努力研发中",
    icon: "none",
  });
};

// 创建响应式数据
const setshow = ref(false);

// 定义方法
function open() {
  // 打开逻辑，比如设置 show 为 true
  setshow.value = true;
  // console.log('open');
}

function close() {
  // 关闭逻辑，设置 show 为 false
  setshow.value = false;
  // console.log('close');
}
const num = ref({
  warn_value: 0,
});
const rules = ref({
  // 字段名称
  warn_value: [
    {
      required: true,
      message: "请输入数量",
      trigger: ["change", "blur"],
    },
    {
      pattern: /^[0-9]*$/g,
      // 正则检验前先将值转为字符串
      transform(value) {
        return String(value);
      },
      message: "请输入整数",
    },
  ],
});
const daytype = ref(1);
const profit = ref(0);
const total = ref(0);
const total_price = ref(0);
const statisticsfun = () => {
  statistics({ shop_id: selectshopid.value, day: daytype.value }).then(
    (res) => {
      profit.value = res.data.profit;
      total.value = res.data.total;
      total_price.value = res.data.total_price;
      order_count.value = res.data.order_count;
      let data = [];
      let data1 = [];
      let data2 = [];
      let data3 = [];
      res.data.list.forEach((item) => {
        data.push(item.month.slice(2, 10));
        data1.push(item.total <= 0 ? "" : item.total);
        data2.push(item.total_price <= 0 ? "" : item.total_price);
        data3.push(item.profit <= 0 ? "" : item.profit);
      });

      nextTick(() => {
        let res = {
          categories: data,
          series: [
            {
              name: "销售数量",
              data: data1,
            },
            {
              name: "销售额",
              data: data2,
            },
            {
              name: "利润",
              data: data3,
            },
          ],
        };

        chartData.value = JSON.parse(JSON.stringify(res));
      });
    }
  );
};
const setnumfun = () => {
  if (num.value.warn_value < 1) {
    return uni.showToast({
      title: "请输入大于0的整数",
      icon: "none",
    });
  }
  if (num.value.warn_value > selectshopobj.value.quota) {
    return uni.showToast({
      title: "请输入小于的配额数量",
      icon: "none",
    });
  }
  shopEdit({
    shop_id: selectshopid.value,
    warn_value: num.value.warn_value,
  })
    .then((res) => {
      selectshopobj.value.warn_value = num.value.warn_value;
      setshow.value = false;
      uni.showToast({
        title: "设置成功",
        icon: "none",
      });
    })
    .catch((err) => {
      uni.showToast({
        title: err.info,
        icon: "none",
      });
    });
};

const gosetfun = () => {
  num.value.warn_value = selectshopobj.value.warn_value;
  setshow.value = true;
};

const selecttime = (index) => {
  daytype.value = index;
  statisticsfun();
};

const gocode = () => {
  uni.navigateTo({
    url:
      "/pages/team/promotion-code/Index?shop_id=" +
      selectshopid.value +
      "&shop_name=" +
      encodeURIComponent(selectshopobj.value.shop_name),
  });
};
//销售订单
const goorderfun = () => {
  uni.navigateTo({
    url: "/pages/team/orderlist/index?shop_id=" + selectshopid.value,
  });
};
const gocoumt = () => {
  uni.navigateTo({
    url: "/pages/team/coumt/index?shop_id=" + selectshopid.value,
  });
};

nextTick(() => {
  // let res = {
  //   categories: ["2018", "2019", "2020", "2021", "2022", "2023"],
  //   series: [
  //     {
  //       name: "成交量A",
  //       data: [35, 8, 25, 37, 4, 20],
  //     },
  //     {
  //       name: "成交量B",
  //       data: [70, 40, 65, 100, 44, 68],
  //     },
  //     {
  //       name: "成交量C",
  //       data: [100, 80, 95, 150, 112, 132],
  //     },
  //   ],
  // };
  // chartData.value = JSON.parse(JSON.stringify(res));
});
</script>
<template>
  <view class="work">
    <view class="work-banner">
      <view class="work-banner-list">
        <view class="list-index">
          <view class="list-index-left">库存管理</view>
          <view class="list-index-right" @click="getSelectShopfun">
            <text>{{ selectshopname }}</text>
            <up-icon
              name="arrow-down"
              color="#6f6f6f"
              size="30rpx"
              style="margin-left: 10rpx"
            >
            </up-icon>
          </view>
        </view>
      </view>
      <view class="user-order user-list-gn">
        <view class="user-order-item">
          <view class="user-order-item-left">
            <view>剩余库存</view>
            <view class="user-order-item-left-num" @click="gokcfun">
              <text>{{ (selectshopobj && selectshopobj.stock) || 0 }}</text>
              <up-icon
                name="arrow-right"
                color="#6f6f6f"
                size="32rpx"
              ></up-icon>
            </view>
          </view>
          <view class="user-order-item-right">
            <text
              >低于{{
                (selectshopobj && selectshopobj.warn_value) || 0
              }}盒自动补货，配额{{
                (selectshopobj && selectshopobj.quota) || 0
              }}盒
              <!-- <text class="red-text">设置</text> -->
            </text>
            <!-- <up-icon name="arrow-right" color="#6f6f6f" size="30rpx"></up-icon> -->
          </view>
        </view>
        <!-- <view
          class="user-order-item"
          v-for="(item, index) in list"
          :key="index"
          @click="newPage(item)"
        >
          <uni-badge
            class="uni-badge-left-margin"
            :text="item.num"
            absolute="rightTop"
            size="small"
          >
            <image :src="item.icon" mode="widthFix" />
            <view class="user-order-name">{{ item.name }}</view></uni-badge
          >
        </view> -->

        <!-- <view class="user-order-item">
          <uni-badge
            class="uni-badge-left-margin"
            :text="0"
            absolute="rightTop"
            size="small"
          >
            <up-icon
              style="justify-content: center"
              name="grid-fill"
              color="#2979ff"
              size="60rpx"
            ></up-icon>
            <view class="user-order-name"> 店铺二维码 </view></uni-badge
          >
        </view> -->
      </view>
    </view>
    <!-- <view class="work-banner">
      <view class="work-banner-list">
        <view class="list-index">
          <view class="list-index-left">团队管理</view>
        </view>
      </view>
      <view class="user-order user-list-gn">
        <view
          class="user-order-item"
          v-for="(item, index) in teamList"
          :key="index"
          @click="newPage(item)"
        >
          <image :src="item.icon" mode="widthFix" />
          <view class="user-order-name">{{ item.name }}</view>
        </view>
        <view
          class="user-order-item"
          v-for="(item, index) in teamList2"
          :key="index"
          @click="newPage(item)"
        >
          <image :src="item.icon" mode="widthFix" />
          <view class="user-order-name">{{ item.name }}</view>
        </view>
      </view>
    </view> -->

    <!-- <view class="work-banner">
      <view class="foodr-list">
        <view class="list-index">
          <view class="list-index-left">我的收入</view>
          <view class="list-index-right" @click="godetlist"
            >余额变动明细
            <image
              src="@/static/team/shopkeeper/icon-gm11.png"
              mode="widthFix"
            ></image>
          </view>
        </view>
      </view>

      <u-line></u-line>
      <view class="work-middle">
        <view class="work-middle-left">
          <view class="middle-left-top">账户余额（元）</view>
          <view class="middle-left-footer"
            >￥{{ formatPrice(balance.balance || 0) }}</view
          >
        </view>
        <view class="work-middle-right">
          <view class="middle-right-bt" @click="gopayment">代付</view>
          <view class="middle-right-bt withdrawal" @click="gobalance"
            >提现</view
          >
        </view>
      </view>
      <u-line></u-line>

      <view class="work-banner-footer">
        <view class="work-footer-box">
          <view class="left-box">
            <view class="work-left-text">预估收入</view>
            <view class="work-middle-img">
              <uni-tooltip
                class="item"
                content="未出账的预估收益"
                placement="right"
              >
                <view class="item">
                  <u-icon name="question-circle"></u-icon
                ></view>
              </uni-tooltip>
            </view>
            <view class="work-money" @click="goygfun"
              >￥{{ formatPrice(balance.expected_reward || 0) }}</view
            >
          </view>
        </view>
        <view class="work-footer-box">
          <view class="left-box">
            <view class="work-left-text">提现中</view>
            <view class="work-money"
              >￥{{ formatPrice(balance.settle_balance || 0) }}</view
            >
          </view>
        </view>
      </view>
    </view> -->

    <!-- <view class="work-banner" @click="goinvoice">
      <view class="foodr-list">
        <view class="list-index">
          <view class="list-index-left1">
            <image
              src="@/static/team/invoice-icon.png"
              mode="widthFix"
            />开具发票</view
          >
          <view class="list-index-right">
            <image
              src="@/static/team/shopkeeper/icon-gm11.png"
              mode="widthFix"
            ></image>
          </view>
        </view>
      </view>
    </view> -->

    <view class="work-st">
      <view class="work-st-title">营业统计</view>
      <view class="work-st-bt">
        <view class="bt-index" @click="gocode">收款码</view>
        <!-- order_count -->
        <uni-badge
          class="bt-index"
          :text="order_count"
          absolute="rightTop"
          size="small"
          :offset="[10, 9]"
        >
          <view @click="goorderfun" class="bt-index-bt">销售订单</view>
        </uni-badge>
      </view>

      <view class="work-st-num">
        <view class="work-st-num-time">
          <text
            @click="selecttime(1)"
            :class="daytype == 1 ? 'select-time' : ''"
            >今日</text
          >
          <text
            @click="selecttime(2)"
            :class="daytype == 2 ? 'select-time' : ''"
            >昨日</text
          >
          <text
            @click="selecttime(3)"
            :class="daytype == 3 ? 'select-time' : ''"
            >本月</text
          >
        </view>
        <view class="work-st-num-money">
          <view class="work-st-num-money-item" @click="gocoumt()">
            <view class="work-st-num-money-item-name">销售数量</view>
            <view class="work-st-num-money-item-num">{{ total || 0 }}</view>
          </view>
          <view class="work-st-num-money-item" @click="gocoumt()">
            <view class="work-st-num-money-item-name">销售金额</view>
            <view class="work-st-num-money-item-num">{{
              total_price || 0
            }}</view>
          </view>
          <view class="work-st-num-money-item" @click="gocoumt()">
            <view class="work-st-num-money-item-name">利润</view>
            <view class="work-st-num-money-item-num">{{ profit || 0 }}</view>
          </view>
        </view>
      </view>
    </view>

    <view class="echart-k">
      <view></view>
      <qiun-data-charts type="line" :opts="opts" :chartData="chartData" />
    </view>
  </view>
  <u-picker
    :show="show"
    :columns="columns"
    keyName="shop_name"
    :closeOnClickOverlay="true"
    @close="closefun"
    @confirm="confirmfun"
    @cancel="show = false"
  ></u-picker>

  <u-popup :show="setshow" @close="close" @open="open" mode="top" round="15">
    <view class="setcontent">
      <view class="setcontent-title">设置自动补货</view>
      <view class="setcontent-desc">
        补货物流运输周期为2～4天左右 当前配额最大100，增加配额请联系客服</view
      >
      <up-form labelPosition="left" :model="num" :rules="rules" ref="form1">
        <up-form-item label="数量" prop="warn_value" borderBottom ref="item1">
          <up-input v-model="num.warn_value" type="number"></up-input>
        </up-form-item>
      </up-form>
      <view class="setcontent-ts"
        >库存低于{{ num.warn_value || 0 }}自动提交补货申请</view
      >
      <view class="setbtn">
        <button class="qx-bt" @click="setshow = false">取消</button>
        <button class="qr-bt" @click="setnumfun">确认</button>
      </view>
    </view>
  </u-popup>
</template>

<style lang="scss" scoped>
@import "./work.scss";
</style>
